<template>
  <div class="app-container">
    <!-- 使用 el-card 添加外框线 -->
    <el-card v-show="showSearch">
      <!-- 搜索表单 -->
      <el-form ref="formRef" :model="form" label-width="80px">
        <el-row :gutter="20" style="margin-bottom: 18px;">
          <el-col :span="6">
            <el-form-item label="站点名称">
              <el-input v-model="form.siteName" placeholder="请输入站点名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="站点类型">
              <el-select v-model="form.siteType" placeholder="请选择">
                <el-option :label="item.name" :value="item.id" v-for="item in siteInfoTypeSelect"
                  :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属系统">
              <el-select v-model="form.systemId" placeholder="请选择">
                <el-option :label="item.name" :value="item.id" v-for="item in siteTypeAppSelect"
                  :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="站点状态">
              <el-select v-model="form.siteStatus" placeholder="请选择">
                <el-option :label="item.dictLabel" :value="item.dictValue" v-for="item in siteInfoStatusSelect"
                  :key="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card style="margin-top: 20px;">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="addBasicSiteInfoShow"
            v-hasPermi="['system:role:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleEdit"
            v-hasPermi="['system:role:edit']">修改</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="handleSearch" :columns="columns"></right-toolbar>
      </el-row>
      <!-- 数据表格 -->
      <el-table :data="tableData" @selection-change="handleSelectionChange" style="width: 100%; margin-top: 20px;">
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column type="index" label="序号" width="55" align="center" v-if="columns[0].visible" />
        <el-table-column prop="siteName" align="center" label="站点名称" v-if="columns[1].visible" />
        <el-table-column prop="siteTypeName" align="center" label="站点类型" v-if="columns[2].visible">
          <template #default="scope">
            <el-tag>{{ scope.row.siteTypeName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="systemId" align="center" label="所属系统" v-if="columns[3].visible">
          <template #default="scope">
            <el-tag>{{siteTypeAppSelect.find(item => item.id == scope.row.systemId)?.name}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="regionId" align="center" label="所属区域" v-if="columns[4].visible">
          <template #default="scope">
            <el-tag>{{siteInfoAreaSelect.find(item => item.id == scope.row.regionId)?.name}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="siteAddress" align="center" label="站点地址" v-if="columns[5].visible"></el-table-column>
        <el-table-column prop="contactPerson" align="center" label="联系人" v-if="columns[6].visible"></el-table-column>
        <el-table-column prop="contactPhone" align="center" label="联系电话" v-if="columns[7].visible"></el-table-column>
        <el-table-column prop="siteStatus" align="center" label="站点状态" v-if="columns[8].visible">
          <template #default="scope">
            <el-tag :type="['success', 'primary', 'danger'][scope.row.siteStatus]">
              {{siteInfoStatusSelect.find(item => item.dictValue == scope.row.siteStatus)?.dictLabel}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" v-if="columns[9].visible">
          <template #default="scope">
            <el-button type="text" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" icon="Delete" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px;">
        <el-pagination v-model:current-page="form.pageNum" v-model:page-size="form.pageSize"
          :page-sizes="[10, 20, 30, 40]" background layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
    <!-- 新建站点 -->
    <el-dialog title="新建站点" v-model="addAndUpdateFormVisible" style="width: 600px;">
      <el-form ref="formRef" :model="addAndUpdateForm" label-width="120px" :rules="rules" style="width: 100%;">
        <!-- 站点名称 -->
        <el-form-item label="站点名称" prop="siteName">
          <el-input v-model="addAndUpdateForm.siteName" placeholder="请输入站点名称"></el-input>
        </el-form-item>
        <!-- 站点类型 -->
        <el-form-item label="站点类型" prop="siteType">
          <el-select v-model="addAndUpdateForm.siteType" placeholder="请选择站点类型">
            <el-option :label="item.name" :value="item.id + ''" v-for="item in siteInfoTypeSelect"
              :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 所属系统 -->
        <el-form-item label="所属系统" prop="systemId">
          <el-select v-model="addAndUpdateForm.systemId" placeholder="请选择所属系统">
            <el-option :label="item.name" :value="item.id" v-for="item in siteTypeAppSelect" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 站点状态 -->
        <el-form-item label="站点状态" prop="siteStatus">
          <el-select v-model="addAndUpdateForm.siteStatus" placeholder="请选择站点状态">
            <el-option :label="item.dictLabel" :value="item.dictValue" v-for="item in siteInfoStatusSelect"
              :key="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <!-- 所在区域 -->
        <el-form-item label="所在区域" prop="regionId">
          <el-select v-model="addAndUpdateForm.regionId" placeholder="请选择所在区域">
            <el-option :label="item.name" :value="+item.id" v-for="item in siteInfoAreaSelect"
              :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 站点坐标 -->
        <el-form-item label="站点坐标">
          <div>
            <span>点击确定位置坐标</span>
            ----
            <span>当前已选的经纬度为：</span>
            <span>{{ addAndUpdateForm.latitude }}, {{ addAndUpdateForm.longitude }}</span>
          </div>
          <div id="container">
            <aMap @changeMapForm="handleChangeMapForm" @clickMapForm="clickMapForm"
              :center="[109.73592900021262, 18.748247996638018]" />
          </div>
          <div class="lat_lng">
            <div class="item">
              <p>经度：</p>
              <div>
                <el-input v-model="mapForm.Lat"></el-input>
              </div>
            </div>
            <div class="item">
              <p>纬度：</p>
              <div>
                <el-input v-model="mapForm.Lng"></el-input>
              </div>
            </div>
          </div>
        </el-form-item>
        <!-- 联系人 -->
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="addAndUpdateForm.contactPerson" placeholder="请输入联系人"></el-input>
        </el-form-item>

        <!-- 联系电话 -->
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="addAndUpdateForm.contactPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <!-- 联系邮箱 -->
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="addAndUpdateForm.contactEmail" placeholder="请输入联系邮箱"></el-input>
        </el-form-item>
        <!-- 站点地址 -->
        <el-form-item label="站点地址" prop="siteAddress">
          <el-input type="textarea" v-model="addAndUpdateForm.siteAddress" placeholder="请输入站点地址"></el-input>
        </el-form-item>
        <!-- 备注信息 -->
        <el-form-item label="备注信息" prop="remark">
          <el-input type="textarea" v-model="addAndUpdateForm.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="addAndUpdateFormSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { listBasicSiteInfo, updateBasicSiteInfo, addBasicSiteInfo, delBasicSiteInfo, getBasicSiteInfoStatusSelect, getBasicSiteTypeAppSelect, getBasicSiteInfoAreaSelect, getBasicSiteInfoTypeSelect, getBasicSiteInfo } from '@/api/basic/site/basicSiteInfo.js';
import aMap from '@/components/aMap/index.vue';
import { ElLoading, ElMessage } from 'element-plus'
import { add } from 'three/src/nodes/TSL.js';

const showSearch = ref(true);

// 列显隐信息
const columns = ref([
  { key: 0, label: `序号`, visible: true },
  { key: 1, label: `站点名称`, visible: true },
  { key: 2, label: `站点类型`, visible: true },
  { key: 3, label: `所属系统`, visible: true },
  { key: 4, label: `所属区域`, visible: true },
  { key: 5, label: `站点地址`, visible: true },
  { key: 6, label: `联系人`, visible: true },
  { key: 7, label: `联系电话`, visible: true },
  { key: 8, label: `站点状态`, visible: true },
  { key: 9, label: `操作`, visible: true },
]);

const formRef = ref();
const rules = ref({
  siteName: [
    { required: true, message: '请输入检测量名称', trigger: 'blur' },
  ],
  siteType: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  systemId: [
    { required: true, message: '请选择', trigger: 'change' }
  ],
  regionId: [
    { required: true, message: '请选择', trigger: 'change' }
  ],
  siteStatus: [
    { required: true, message: '请选择', trigger: 'change' }
  ]
});
// 新增：重置表单函数
const resetForm = () => {
  // 清空表单数据
  addAndUpdateForm.value = {
    siteName: '',
    siteType: '',
    systemId: '',
    regionId: '',
    siteStatus: '',
    siteAddress: '',
    latitude: '',
    longitude: '',
    contactPerson: '',
    contactPhone: '',
    contactEmail: '',
    remark: '',
    siteId: '' // 清空siteId，区分新增和编辑状态
  };
  // 清空地图坐标
  mapForm.value = {
    Lng: '',
    Lat: ''
  };
  // 重置表单验证状态
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 新增：取消按钮处理函数
const handleCancel = () => {
  resetForm();
  addAndUpdateFormVisible.value = false;
};


const mapForm = ref({
  Lng: '',
  Lat: ''
});

const form = ref({
  siteName: '',
  siteType: '',
  systemId: '',
  regionId: '',
  siteStatus: '',
  pageNum: 1,
  pageSize: 10
});

const addAndUpdateForm = ref({
  siteName: '',
  siteType: '',
  systemId: '',
  regionId: '',
  siteStatus: '',
  siteAddress: '',
  latitude: '',
  longitude: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  remark: ''
});

const addAndUpdateFormVisible = ref(false);
const tableData = ref([]);
const siteInfoStatusSelect = ref([]);
const siteInfoTypeSelect = ref([]);
const siteInfoAreaSelect = ref([]);
const siteTypeAppSelect = ref([]);
const total = ref(0);
const multipleSelection = ref('');

// 选的经纬度
const clickMapForm = (args) => {
  addAndUpdateForm.value.latitude = args.Lat;
  addAndUpdateForm.value.longitude = args.Lng;
}
const handleSearch = () => {
  listBasicSiteInfo(form.value).then((response) => {
    tableData.value = response.rows;
    total.value = response.total;
  })
};

const handleReset = () => {
  form.value = {
    siteName: '',
    siteType: '',
    systemId: '',
    regionId: '',
    siteStatus: ''
  };
};


const handleEdit = (row) => {
  const siteId = row.siteId || ids.value;
  console.log('Edit:', row);
  getBasicSiteInfo(siteId).then((response) => {
    addAndUpdateForm.value = response.data;
    addAndUpdateFormVisible.value = true;
  })

};
// 批量删除
const handleBulkDelete = () => {
  if (!multipleSelection.value) {
    return
  };
  ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    delBasicSiteInfo(multipleSelection.value).then(() => {
      handleSearch();
    })
  })
};

// 批量选择
// const handleSelectionChange = (val) => {
//   multipleSelection.value = val.map((item) => item.siteId).join(',');

// }
const single = ref(true);
const ids = ref([])
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.siteId);
  single.value = selection.length != 1;
}
// 删除
const handleDelete = (index, row) => {
  ElMessageBox.confirm('是否确认删除序号为"' + (index + 1) + '"的数据项?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delBasicSiteInfo(row.siteId).then(() => {
      ElMessage.success('删除成功');
      handleSearch();
    })
  })
};
// 分页
const handleSizeChange = (size) => {
  form.value.pageSize = size;
  handleSearch();

};
const handleCurrentChange = (page) => {
  form.value.pageNum = page;
  handleSearch();

};

getBasicSiteInfoStatusSelect().then((response) => {
  console.log(response);

  siteInfoStatusSelect.value = response.data;
})

getBasicSiteInfoTypeSelect().then((response) => {
  console.log(response);

  siteInfoTypeSelect.value = response.data;
})

getBasicSiteInfoAreaSelect().then((response) => {
  console.log(response);

  console.log(response);

  siteInfoAreaSelect.value = response.data;
})
getBasicSiteTypeAppSelect().then((response) => {
  siteTypeAppSelect.value = response.data;
})
handleSearch();

const handleChangeMapForm = (data) => {
  mapForm.value = data;
}
// 新建站点
const addBasicSiteInfoShow = () => {
  addAndUpdateFormVisible.value = true;
}
watch(
  () => addAndUpdateFormVisible.value,
  (newVal) => {
    // 当弹窗从显示变为隐藏时（newVal为false），执行重置
    if (!newVal) {
      resetForm();
    }
  }
);
// 添加站点
const addAndUpdateFormSubmit = () => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      if (addAndUpdateForm.value.siteId) {
        updateBasicSiteInfo(addAndUpdateForm.value).then(() => {
          handleSearch();
        })
      } else {
        addBasicSiteInfo(addAndUpdateForm.value).then(() => {
          handleSearch();

        })
      }
      addAndUpdateFormVisible.value = false;
    }
  })

}
</script>

<style scoped>
.box-card {
  width: 100%;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.el-card :deep(.el-form-item) {
  margin-bottom: 0px;
}


#container {
  width: 100%;
  height: 240px;
  border-radius: 8px;
  position: relative;
}

.lat_lng {
  /* width: 180px;
  height: 80px; */
  position: absolute;
  bottom: 20px;
  left: 10px;
  line-height: 10px;
  background: #fff;
  padding: 5px 10px;
  border-radius: 10px;
}

.lat_lng .item {
  display: flex;
  align-items: center;
  color: black;
  justify-content: center;
}

.lat_lng .item .el-input {
  width: 100px;
}
</style>